﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.Display;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.Storage.Search;
using Windows.Storage.Streams;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media.Imaging;

namespace LFMTest
{
    public sealed partial class ToolsTest
    {
        List<MusicStorageFile> musicList = new List<MusicStorageFile>();

        public ToolsTest()
        {
            InitializeComponent();
            StartSearch();
        }

        //private async void InitializeMusicSearch()
        //{
        //    MusicSearchOptions = new QueryOptions(CommonFolderQuery.GroupByArtist);
        //    await LoadMusicLibrary();
        //}

        //public async Task LoadMusicLibrary()
        //{
        //    var FileList = await KnownFolders.MusicLibrary.CreateFolderQueryWithOptions(MusicSearchOptions).GetFoldersAsync();
        //    ObservableList Albums = new ObservableList();
        //    foreach (var item in FileList)
        //    {
        //        try
        //        {
        //            StorageFolder file = item as StorageFolder;

        //            var properties = await file.Properties.GetMusicPropertiesAsync();

        //            var foldername = await file.GetFoldersAsync();
        //            ThumbnailMode thumbnailMode = ThumbnailMode.MusicView;
        //            uint size = 100;
        //            StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, size);

        //            BitmapImage AlbumThumb = new BitmapImage();
        //            AlbumThumb.SetSource(thumbnail);


        //            Albums.Add(new BindableStorageFile { Name = properties.Artist, ThumbNail = AlbumThumb, Folder = file });
        //        }
        //        catch (Exception eee)
        //        {
        //            Debug.WriteLine(eee);
        //        }
        //        MusicListView.ItemsSource = Albums;
        //    }
        //}

        QueryOptions msqo = new QueryOptions();

        private async void StartSearch()
        {
            msqo = new QueryOptions(CommonFileQuery.OrderByMusicInfo, new List<String> { ".mp3" });
            await LoadMusicLibrary();
        }

        private async void ArtistAlbums(String e)
        {
            QueryOptions q = new QueryOptions(CommonFolderQuery.GroupByAlbumArtist);
            await getAlbums(q, e); 
        }

        private async Task getAlbums(QueryOptions q, string e)
        {
            var folders = await Windows.Storage.KnownFolders.MusicLibrary.CreateFolderQueryWithOptions(msqo).GetFoldersAsync();
            foreach (var item in folders)
            {
                StorageFolder f = item as StorageFolder;
                var p = await f.Properties.GetMusicPropertiesAsync();

                p.
            }
            
        }

        private async Task LoadMusicLibrary()
        {
            var filesList = await Windows.Storage.KnownFolders.MusicLibrary.CreateFileQueryWithOptions(msqo).GetFilesAsync();

            pb_loading.Minimum = 0;
            pb_loading.Maximum = filesList.Count;
            pb_loading.Value = 0;

            int cur = 0;

            foreach (var item in filesList)
            {
                try
                {
                    StorageFile file = item as StorageFile;
                    var p = await file.Properties.GetMusicPropertiesAsync();

                    MusicStorageFile musicFile = new MusicStorageFile
                    {
                        Title = p.Title,
                        Album = p.Album,
                        Artist = p.Artist,
                        Bitrate = p.Bitrate,
                        Duration = p.Duration,
                        Rating = p.Rating,
                        TrackNumber = p.TrackNumber,
                        File = file
                    };

                    //var thumb = await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.MusicView);
                    //BitmapImage bmp = new BitmapImage();
                    //bmp.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                    //bmp.DecodePixelHeight = 150;
                    //bmp.DecodePixelWidth = 150;
                    //InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
                    //RandomAccessStream.Copy(thumb.GetInputStreamAt(0), ras.GetOutputStreamAt(0));
                    //bmp.SetSource((IRandomAccessStream)ras);
                    //musicFile.Thumbnail = bmp;

                    musicList.Add(musicFile);

                    if (cur == 50)
                    {
                        //me_p.Source = new Uri(file.Path, UriKind.Absolute);
                        //break;
                    }

                    //if (cur > 50) break;
                    // UI stuff
                    cur++;
                    pb_loading.Value = cur;
                    tb_loading.Text = String.Format("{0} out of {1} files analysed", cur, pb_loading.Maximum);
                }
                catch
                {
                    Debugger.Break();
                }
            }

            lb_results.ItemsSource = musicList;
        }

        #region View management

        // View state management for switching among Full, Fill, Snapped, and Portrait states

        private DisplayPropertiesEventHandler _displayHandler;
        private TypedEventHandler<ApplicationLayout, ApplicationLayoutChangedEventArgs> _layoutHandler;

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (_displayHandler == null)
            {
                _displayHandler = Page_OrientationChanged;
                _layoutHandler = Page_LayoutChanged;
            }
            DisplayProperties.OrientationChanged += _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged += _layoutHandler;
            SetCurrentOrientation(this);
        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            DisplayProperties.OrientationChanged -= _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged -= _layoutHandler;
        }

        private void Page_LayoutChanged(object sender, ApplicationLayoutChangedEventArgs e)
        {
            SetCurrentOrientation(this);
        }

        private void Page_OrientationChanged(object sender)
        {
            SetCurrentOrientation(this);
        }

        private void SetCurrentOrientation(Control viewStateAwareControl)
        {
            VisualStateManager.GoToState(viewStateAwareControl, this.GetViewState(), false);
        }

        private String GetViewState()
        {
            var orientation = DisplayProperties.CurrentOrientation;
            if (orientation == DisplayOrientations.Portrait ||
                orientation == DisplayOrientations.PortraitFlipped) return "Portrait";
            var layout = ApplicationLayout.Value;
            if (layout == ApplicationLayoutState.Filled) return "Fill";
            if (layout == ApplicationLayoutState.Snapped) return "Snapped";
            return "Full";
        }

        #endregion

        private async void lb_results_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lb_results.SelectedIndex > -1)
            {
                MusicStorageFile m = (MusicStorageFile)lb_results.SelectedItem;

                //me_p.Source = new Uri(m.File.Path, UriKind.RelativeOrAbsolute);

                //var f = await m.File.OpenAsync(FileAccessMode.Read);

                //InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
                //RandomAccessStream.Copy(f.GetInputStreamAt(0), ras.GetOutputStreamAt(0));

                //me_p.SetSource((IRandomAccessStream)ras, "audio/mp3");
            }
        }

        private void me_p_MediaOpened(object sender, RoutedEventArgs e)
        {
           // me_p.Play();
        }

        private async void me_p_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            //tb_loading.Text = me_p.CurrentState.ToString();
        }

        private void b_search_Click(object sender, RoutedEventArgs e)
        {
            var results = musicList.Where(m => m.Artist.ToLower().Contains(tb_Input.Text.ToLower()));
            lb_results2.ItemsSource = results;
        }

        private void b_search3_Click(object sender, RoutedEventArgs e)
        {
            var results = musicList.Where(m => m.Artist.ToLower().Contains(tb_Input3.Text.ToLower())).GroupBy(m => m.Album);
            foreach (MusicStorageFile m in results) Debug.WriteLine(m.Album);
            lb_results3.ItemsSource = results;
        }
    }
}
